<template>
  <a-modal
    :visible="visible"
    title=" 新增"
    cancelText="取消"
    okText="提交"
    @ok="submit"
    @cancel="cancel"
  >
    <a-form
      ref="formRef"
      :labelCol="labelCol"
      :wrapperCol="wrapperCol"
      :model="formData"
      :rules="formRules"
    >
      <a-form-item label="时间" name="time">
        <a-date-picker
          @change="onDateChange"
          v-model:value="formData.time"
          style="width: 80%"
        ></a-date-picker>
      </a-form-item>
      <a-form-item label="施工单位考勤文件" name="fileListOfConstruction">
        <a-upload
          :file-list="fileListOfConstruction"
          :remove="handleRemoveOfConstruction"
          :before-upload="beforeUploadOfConstruction"
        >
          <a-button>
            <upload-outlined></upload-outlined>
            点击上传
          </a-button>
        </a-upload>
      </a-form-item>
      <a-form-item label="监理单位考勤文件" name="fileListOfSupervise">
        <a-upload
          :file-list="fileListOfSupervise"
          :remove="handleRemoveOfSupervise"
          :before-upload="beforeUploadOfSupervise"
        >
          <a-button>
            <upload-outlined></upload-outlined>
            点击上传
          </a-button>
        </a-upload>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { message } from "ant-design-vue";
import { defineProps, defineEmits, ref, watch } from "vue";
import {
  kqglUpload,
  kqglSaveOrUpdate,
} from "@/api/module/constructAndImplement";
import global from "../../../global/global.vue";

// 项目id
const projectId = global.xmid;

const props = defineProps({
  visible: Boolean,
  isDisabled: Boolean,
  editData: Array,
});
const emits = defineEmits(["close"]);

const labelCol = { span: 7 };
const wrapperCol = { span: 17 };

// 表单实例
const formRef = ref();

// 监听传递的数据
watch(
  () => props.editData,
  (newV, oldV) => {
    formData.value = newV;
    if (newV.sgdwkqFile) {
      fileListOfConstruction.value = [
        {
          name: newV.sgdwkqFileName,
          id: newV.sgdwkqFile,
        },
      ];
      fileListOfSupervise.value = [
        {
          name: newV.jldwkqFileName,
          id: newV.jldwkqFile,
        },
      ];
      idOfConstruction.value = newV.sgdwkqFile;
      idOfListOfSupervise.value = newV.jldwkqFile;
    }
  },
  { deep: true }
);

// 表单校验
const constructionValidator = (rule, value, callback) => {
  if (fileListOfConstruction.value.length === 0) {
    return Promise.reject("请上传文件");
  } else {
    return Promise.resolve();
  }
};
const superviseValidator = (rule, value, callback) => {
  if (fileListOfSupervise.value.length === 0) {
    return Promise.reject("请上传文件");
  } else {
    return Promise.resolve();
  }
};
const formRules = {
  time: [{ required: true, message: "请选择", trigger: "change" }],
  fileListOfConstruction: [
    { validator: constructionValidator, trigger: "blur" },
  ],
  fileListOfSupervise: [{ validator: superviseValidator, trigger: "blur" }],
};

// 表单数据
const formData = ref({
  time: "",
});

// 选择日期
const onDateChange = (date, dateString) => {
  formData.value.time = dateString;
};

// 文件上传
const idOfConstruction = ref("");
const idOfListOfSupervise = ref("");
const fileListOfConstruction = ref([]);
const fileListOfSupervise = ref([]);
// 判断文件类型
const allowedTypes = [
  "application/pdf",
  "application/msword",
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  "application/vnd.ms-excel",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
];

// 上传列表的删除
// 公共逻辑
const handleRemove = (fileList, file, id) => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
  id.value = "";
};
// 施工单位
const handleRemoveOfConstruction = (file) => {
  handleRemove(fileListOfConstruction, file, idOfConstruction);
};
// 监理单位
const handleRemoveOfSupervise = (file) => {
  handleRemove(fileListOfSupervise, file, idOfListOfSupervise);
};

// 上传之前操作
// 公共逻辑
const publicBeforeUpload = (fileList, file) => {
  const isType = allowedTypes.includes(file.type);
  if (!isType) {
    return message.error("请选择正确的文件类型!");
  }
  // 限制只上传一个
  fileList.value = [file];
};

// 施工单位
const beforeUploadOfConstruction = (file) => {
  publicBeforeUpload(fileListOfConstruction, file, "1");
  return false;
};
// 监理单位
const beforeUploadOfSupervise = (file) => {
  publicBeforeUpload(fileListOfSupervise, file, "2");
  return false;
};

/* 提交取消 */
// 上传公共逻辑
const publicUpload = async (fileList, id, type) => {
  const formData = new FormData();
  formData.append("file", fileList.value[0]);
  formData.append("type", type);
  const res = await kqglUpload(formData);
  id.value = res.data[type];
};
const submit = async () => {
  await formRef.value.validate();
  if (props.isDisabled) {
    return message.warn("本月已经提交过，请勿重复提交！");
  }
  // 上传文件
  if (!idOfConstruction.value) {
    await publicUpload(fileListOfConstruction, idOfConstruction, "1");
  }
  if (!idOfListOfSupervise.value) {
    await publicUpload(fileListOfSupervise, idOfListOfSupervise, "2");
  }

  const result = await kqglSaveOrUpdate({
    jldwkqFile: idOfConstruction.value,
    sgdwkqFile: idOfListOfSupervise.value,
    time: formData.value.time,
    xmid: projectId,
  });
  if (result.code === 200) {
    message.success("提交成功");
  }
  clearFormData();
  emits("close", false);
};

const cancel = () => {
  clearFormData();
  emits("close", false);
};

// 清除数据和校验
const clearFormData = () => {
  formData.value.time = "";
  fileListOfConstruction.value = [];
  fileListOfSupervise.value = [];
  formRef.value.clearValidate();
};

const tokenKey = localStorage.getItem("token_key");
const token = localStorage.getItem("token");
const headers = {
  Authorization: token,
  "Authorization-key": tokenKey,
};
</script>
